# -*- coding = utf-8 -*-
# @Time    : 2025/4/7 下午12:23
# @Author  : yqk
# @File    : test.py
# @Software: PyCharm
"""
 滑块图像距离计算
"""
import random

import cv2
import numpy as np
import requests
import ddddocr


def distance_cv(slice_url, bg_url):
    """
    :param slice_url: 滑块（缺口）图片地址
    :param bg_url: 背景图地址
    :return: distance
    :rtype:integer
    """
    slice_image = np.asarray(bytearray(requests.get(slice_url).content), dtype=np.uint8)
    slice_image = cv2.imdecode(slice_image, 1)
    slice_image = cv2.Canny(slice_image, 255, 255)

    bg_image = np.asarray(bytearray(requests.get(bg_url).content), dtype=np.uint8)
    bg_image = cv2.imdecode(bg_image, 1)
    bg_image = cv2.pyrMeanShiftFiltering(bg_image, 5, 50)
    bg_image = cv2.Canny(bg_image, 255, 255)

    result = cv2.matchTemplate(bg_image, slice_image, cv2.TM_CCOEFF_NORMED)

    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    return max_loc[0]


def distance_orc(bg_url, slice_url):
    slide = ddddocr.DdddOcr(det=False, ocr=False, show_ad=False)
    slide_image = requests.get(slice_url).content
    bg_image = requests.get(bg_url).content
    result = slide.slide_match(slide_image, bg_image, simple_target=True)
    # 返回距离
    return result['target'][0]


def distance_puzzle(bg_img_path, puzzle_img_path):
    """
    根据背景图和缺口图，计算滑块距离
    :param bg_img_path:
    :param puzzle_img_path:
    :return:
    """
    img = cv2.imdecode(np.fromfile(bg_img_path, dtype=np.uint8), cv2.IMREAD_COLOR)
    tpl = cv2.imdecode(np.fromfile(puzzle_img_path, dtype=np.uint8), cv2.IMREAD_COLOR)

    img_gry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    _, img_bw = cv2.threshold(img_gry, 127, 255, cv2.THRESH_BINARY)

    tpl = cv2.cvtColor(tpl, cv2.COLOR_BGR2GRAY)
    for row in range(tpl.shape[0]):
        for col in range(tpl.shape[1]):
            if tpl[row, col] == 0:
                tpl[row, col] = 96
    lower = np.array([96])
    upper = np.array([96])
    mask = cv2.inRange(tpl, lower, upper)
    tpl[mask == 0] = 0
    tpl[mask != 0] = 255

    result = cv2.matchTemplate(img_bw, tpl, cv2.TM_CCOEFF_NORMED)
    _, _, _, max_loc = cv2.minMaxLoc(result)
    distance = int(max_loc[0] * 0.5833333333333333) + random.randint(0, 2)
    return distance